<template xmlns="http://www.w3.org/1999/html">
  <div class="page-wrapper">
    <!-- Page body -->
    <div class="page-body">
      <div class="container-xl">
        <div class="row row-deck row-cards">

          <div class="col-12">
            <div class="card">
              <div class="card-header">
                <div class="row g-2 align-items-center">
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-primary w-100" @click="openAddPlugin"
                       data-bs-target="#modal-add-machine">
                      新增插件
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-info w-100" @click="openEditPlugin">
                      修改插件
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-secondary w-100" @click="confirmDelete">
                      删除插件
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-warning w-100" @click="changePluginStatus('启用', 1)">
                      启用
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-secondary w-100" @click="changePluginStatus('禁用', 0)">
                      禁用
                    </a>
                  </div>
                </div>
              </div>
              <div class="card-body border-bottom py-3">
                <div class="d-flex">
                  <div class="text-secondary">
                    {{ tableData.length }}

                    entries
                  </div>
                  <div class="ms-auto text-secondary">
                    Search:
                    <div class="ms-2 d-inline-block">
                      <input type="text" class="form-control form-control-sm" aria-label="Search invoice"
                             placeholder="预留框，暂时无用">
                    </div>
                  </div>
                </div>
              </div>
              <div class="table-responsive">
                <table class="table card-table table-vcenter text-nowrap datatable">
                  <thead>
                  <tr>
                    <th><input class="form-check-input m-0 align-middle" type="checkbox" v-model="isAllChecked"
                               @change="handleToggleAllCheckboxes"></th>
                    <th class="w-1">ID</th>
                    <th>程序名</th>
                    <th>版本号</th>
                    <th>文件名</th>
                    <th>文件类型</th>
                    <th>文件大小</th>
                    <th>链接</th>
                    <th>状态</th>
                    <th>最后修改时间</th>
                    <th>备注</th>
                  </tr>
                  </thead>
                  <tbody>

                  <!-- 使用 v-for 指令循环渲染表格行 -->
                  <tr v-for="(item, index) in tableData" :key="index" @click="toggleRowCheckbox(item)"
                      :class="{'selected-row': item.checked}">
                    <td><input class="form-check-input m-0 align-middle" type="checkbox" v-model="item.checked" @click.stop></td>
                    <td><span class="text-secondary">{{ item.id }}</span></td>
                    <td>{{ item.name }}</td>
                    <td>{{ item.version }}</td>
                    <td>{{ item.fileName }}</td>
                    <td>{{ item.fileType }}</td>
                    <td>{{ item.fileSizeStr }}</td>
                    <td><a :href="item.url" target="_blank">下载</a></td>
                    <td>
                      <span :class="{
                        'badge': true,
                        'bg-green-lt': item.status === 1,
                        'bg-red-lt': item.status === 0
                      }">
                        {{ item.status === 1 ? '启用' : (item.status === 0 ? '禁用' : item.status) }}
                      </span>
                    </td>
                    <td>{{ item.lastUpdateTime }}</td>
                    <td :title="item.remark">
                      {{ truncateText(item.remark, 30) }}
                    </td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>


        </div>

      </div>

    </div>

  </div>


  <!-- 使用封装的模态框组件 -->
  <ComponentModal
      :modalId="'modal-success-machine'"
      :title="'信息'"
      :message="'操作成功'"
      :cancelText="'取消'"
      :confirmText="'确定'"
      ref="componentModalOutRef"
  />

  <AddPluginModal ref="addPluginModalRef"/>
  <EditPluginModal ref="editPluginModalRef" :typeList="typeList" @update-success="fetchData"/>
  <Loading ref="loadingRef"/>


</template>

<script setup>
import {ref, reactive, onMounted, computed, inject, nextTick, watch} from 'vue';
import ComponentModal from '@/components/ComponentModal.vue';
import Loading from '@/components/Loading.vue';
import AddPluginModal from "./AddPluginModal.vue";
import EditPluginModal from "./EditPluginModal.vue";
import { useTableMixin } from '@/mixins/tableMixin';

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
// 表格数据和分页信息
const tableData = ref([]);
const isAllChecked = ref(false);
const typeList = ref([]); // 添加类型列表

const addPluginModalRef = ref(null);
const editPluginModalRef = ref(null);
const componentModalOutRef = ref(null);
const loadingRef = ref(null);

const { 
  toggleAllCheckboxes,
  toggleRowCheckbox,
  getSelectedIds,
  hasSelectedItems,
  resetSelection 
} = useTableMixin();

// 启用,禁用
const changePluginStatus = (text, status) => {
  let ids = [];
  tableData.value.forEach(item => {
    if (item.checked) {
      ids.push(item.id);
    }
  });
  if (ids.length > 0) {
    const idStr = ids.join(',');
    componentModalOutRef.value.openWarnModal(`确定${text} ${idStr} 的插件吗?`, async () => {
      try {
        let url = `${apiBaseUrl}/resident/plugin/status?status=${status}&pluginIds=${idStr}`;
        const response = await fetch(url, {
          method: 'POST'
        });
        const data = await response.json();
        if (data.success) {
          componentModalOutRef.value.openInfoModal(`${text}成功！`);
        }
      } catch (error) {
        componentModalOutRef.value.openWarnModal(`${text}失败！`);
      }
      fetchData();
    });
  } else {
    componentModalOutRef.value.openWarnModal('请选择需要操作的元素');
  }
}

// 处理全选/全不选逻辑
const handleToggleAllCheckboxes = () => {
  toggleAllCheckboxes(tableData.value, isAllChecked.value);
};

// 监听表格数据变化，更新全选状态
watch(tableData, () => {
  isAllChecked.value = tableData.value.length > 0 && tableData.value.every(item => item.checked);
}, { deep: true });

// 处理确认事件
const confirmDelete = () => {
  const delIds = getSelectedIds(tableData.value);
  if (delIds.length > 0) {
    componentModalOutRef.value.openWarnModal('确定删除' + delIds.join(', ') + '的插件吗?', async () => {
      try {
        let deleteUrl = apiBaseUrl + '/resident/plugin/delete?pluginIds=' + delIds.join(',');
        const response = await fetch(deleteUrl, {
          method: 'DELETE'
        });
        const data = await response.json();
        if (data.success) {
          componentModalOutRef.value.openInfoModal('删除成功！');
        }
      } catch (error) {
        componentModalOutRef.value.openWarnModal('删除失败！');
      }
      fetchData();
    });
  } else {
    componentModalOutRef.value.openWarnModal('请选择元素');
  }
};

const openAddPlugin = () => {
  addPluginModalRef.value.openModal();
}

const openEditPlugin = () => {
  const selectedItems = tableData.value.filter(item => item.checked);
  if (selectedItems.length !== 1) {
    componentModalOutRef.value.openWarnModal('请选择一条记录进行修改');
    return;
  }
  editPluginModalRef.value.openModal(selectedItems[0]);
};

const fetchData = async () => {
  try {
    // 模拟API请求，替换为实际API调用
    fetch(apiBaseUrl + '/resident/plugin/search')
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            tableData.value = data.result;
          }
        })
        .catch(error => {
          componentModalOutRef.value.openWarnModal('加载插件数据失败，请稍后重试！');
        });
    ;

  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

// 获取类型列表
const fetchTypeList = async () => {
  try {
    const response = await fetch(apiBaseUrl + '/resident/plugin-label/search');
    const data = await response.json();
    if (data.success) {
      typeList.value = data.result.map(item => ({
        id: item.id,
        name: item.name
      }));
    }
  } catch (error) {
    console.error('Error fetching type list:', error);
    componentModalOutRef.value.openWarnModal('加载类型列表失败，请稍后重试！');
  }
};

// 添加文本截断函数
const truncateText = (text, length) => {
  if (!text) return '';
  return text.length > length ? text.substring(0, length) + '...' : text;
};

onMounted(() => {
  fetchData();
  fetchTypeList(); // 获取类型列表
});

</script>

<style scoped>
/* 状态样式 */
.bg-green-lt {
  background-color: rgba(40, 167, 69, 0.15) !important;
  color: #2fb344 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-red-lt {
  background-color: rgba(220, 53, 69, 0.15) !important;
  color: #d63939 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

/* 表格样式优化 */
.table td {
  padding: 0.75rem;
  vertical-align: middle;
}

.table th {
  font-weight: 600;
  background-color: #f8f9fa;
  border-bottom: 2px solid #dee2e6;
}

.badge {
  display: inline-block;
  font-weight: 500;
  line-height: 1.2;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
}

/* 添加备注列的样式 */
td[title] {
  cursor: help;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 添加选中行的样式 */
.selected-row {
  background-color: rgba(32, 107, 196, 0.1) !important;
}

tr {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

tr:hover {
  background-color: rgba(32, 107, 196, 0.05);
}

/* 防止点击复选框时触发行点击事件 */
tr input[type="checkbox"] {
  cursor: pointer;
  pointer-events: auto;
}
</style>